package com.renwei.yunlong.activity.news;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.adapter.TablayoutAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.PowerBean;
import com.renwei.yunlong.event.ProblemPageRefreshEvent;
import com.renwei.yunlong.event.ProblemPageStateRefreshEvent;
import com.renwei.yunlong.fragment.BaseHistoryFragment;
import com.renwei.yunlong.fragment.ProblemRelatedFragment;
import com.renwei.yunlong.fragment.WorkDetailsFragment;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.DialogUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import github.opensource.dialog.prompt.PromptButton;
import github.opensource.dialog.prompt.PromptButtonListener;
import github.opensource.dialog.prompt.PromptDialog;

/**
 * 问题信息--页面
 * <p>
 * Created by Administrator on 2017/8/28.
 */

public class ProblemInformationActivity extends BaseActivity implements View.OnClickListener, PromptButtonListener, HttpTaskListener {

    private static final String POWER_SHENLING = "申领";
    private static final String POWER_ZHIPAIGEI = "指派给";
    private static final String POWER_GUANBI = "关闭";
    private static final String POWER_CHULI = "处理";
    private static final String POWER_QUEREN = "确认";
    @Bind(R.id.tab_layout)
    TabLayout mTabLayout;
    @Bind(R.id.v_pager)
    ViewPager mViewPager;
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.btn_next)
    Button btnNext;
    @Bind(R.id.rl_button)
    RelativeLayout rlButton;
    private String questionId; // 问题id
    private String requestId;
    private TablayoutAdapter adapter;
    private PromptDialog promptDialog;
    private HashSet<String> powerSet;
    private String outsourceFlag;
    private boolean isLook;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_problem_information);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        questionId = getIntent().getStringExtra("questionId");
        requestId = getIntent().getStringExtra("requestId");
        outsourceFlag = getIntent().getStringExtra("outsourceFlag");
        isLook = getIntent().getBooleanExtra("isLook", false);

        EventBus.getDefault().register(this);

        initView();
        initData();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefresh(ProblemPageRefreshEvent event) {
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        ivBack.setVisibility(View.VISIBLE);
        tvTitle.setText("问题信息");
        ivBack.setOnClickListener(this);
        btnNext.setOnClickListener(this);

        //页面，数据源
        ArrayList<Fragment> list = new ArrayList<>();
        list.add(new BaseHistoryFragment(questionId,"problem","0"));
        list.add(new ProblemRelatedFragment(questionId));
        list.add(new WorkDetailsFragment(requestId, outsourceFlag, false));
        String[] titles = {"处理过程", "相关问题", "工单详情"};
        //ViewPager的适配器
        adapter = new TablayoutAdapter(getSupportFragmentManager(), list, titles);
        mViewPager.setAdapter(adapter);
        mViewPager.setOffscreenPageLimit(3);
        //绑定
        mTabLayout.setupWithViewPager(mViewPager);
        promptDialog = new PromptDialog(this);
    }

    private void initData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("id", questionId);
        map.put("type", "0");
        ServiceRequestManager.getManager().getProbCompState(this, JsonMapUtil.mapToJson(map), new HttpTaskListener() {
            @Override
            public void onSuccess(int requestId, String result) {
                PowerBean bean = new Gson().fromJson(result, PowerBean.class);
                String nowState = bean.getRows().getNowStat();
                String responseUserId = bean.getRows().getResponseUserId();
                powerSet = new HashSet<>();
                if ("1".equals(companyType)) {
                    if ("12".equals(ownerBean.getRows().getEmployee().getRoleId()) || "10".equals(ownerBean.getRows().getEmployee().getRoleId())) {
                        if ("3".equals(nowState) || "4".equals(nowState) || "-6".equals(nowState)) {
                            //申领  指派给  关闭
                            powerSet.add(POWER_SHENLING);
                            powerSet.add(POWER_ZHIPAIGEI);
                            powerSet.add(POWER_GUANBI);
                        } else if ("2".equals(nowState)) {
                            //确认
                            powerSet.add(POWER_QUEREN);
                        }
                    } else if ("11".equals(ownerBean.getRows().getEmployee().getRoleId())) {
                        if ("3".equals(nowState) || "4".equals(nowState) || "-6".equals(nowState)) {
                            //申领
                            powerSet.add(POWER_SHENLING);
                        }
                    }
                    if ("1".equals(nowState) && responseUserId.equals(ownerBean.getRows().getEmployeeId())) {
                        //处理
                        powerSet.add(POWER_CHULI);
                    }
                } else if ("2".equals(companyType)) {
                    //服务商问题权限
                    if ("12".equals(serviceLoginBean.getRows().getEmployee().getRoleId()) || "10".equals(serviceLoginBean.getRows().getEmployee().getRoleId())) {

                        if ("3".equals(nowState) || "4".equals(nowState) || "-6".equals(nowState)) {
                            //申领  指派给  关闭
                            powerSet.add(POWER_SHENLING);
                            powerSet.add(POWER_ZHIPAIGEI);
                            powerSet.add(POWER_GUANBI);
                        } else if ("2".equals(nowState)) {
                            //确认
                            powerSet.add(POWER_QUEREN);
                        }

                    } else if ("11".equals(serviceLoginBean.getRows().getEmployee().getRoleId())) {
                        if ("3".equals(nowState) || "4".equals(nowState) || "-6".equals(nowState)) {
                            //申领
                            powerSet.add(POWER_SHENLING);
                        }
                    }

                    if ("1".equals(nowState) && serviceLoginBean.getRows().getEmployeeId().equals(responseUserId)) {
                        //处理
                        powerSet.add(POWER_CHULI);
                    }
                }
                if (powerSet.size() == 0) {
                    if (isLook)
                        EventBus.getDefault().post(new ProblemPageStateRefreshEvent(bean.getRows().getNowStat(), false));
                    rlButton.setVisibility(View.GONE);
                } else {
                    if (isLook)
                        EventBus.getDefault().post(new ProblemPageStateRefreshEvent(bean.getRows().getNowStat(), true));
                    rlButton.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onException(int requestId, String code) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_next:
                setDialog();
                break;
            default:
                break;
        }
    }

    //请求里待办事项的处理
    private void setDialog() {
        if (powerSet.size() != 0) {
            PromptButton[] buttons = new PromptButton[powerSet.size() + 1];
            buttons[0] = new PromptButton("取消", null);
            int i = 0;
            for (String s : powerSet) {
                i++;
                buttons[i] = new PromptButton(s, this);
            }
            promptDialog.showBottomAlert("", true, buttons);
        }
    }

    @Override
    public void onClick(PromptButton button) {
        switch (button.getText()) {
            case POWER_SHENLING: // 申领
                showDialog();
                break;
            case POWER_ZHIPAIGEI: // 指派给
                ProblemAssignActivity.OpenActivity(this, "问题指派", questionId, "");
                break;
            case POWER_GUANBI:  // 关闭
                ProblemCloseActivity.OpenActivity(this, questionId);
                break;
            case POWER_QUEREN:  // 确认
                ProblemConfirmActivity.OpenActivity(this, questionId);
                break;
            case POWER_CHULI:  // 处理
                ProblemDealActivity.OpenActivity(this, questionId);
                break;
            default:
                break;
        }
    }

    //显示dialog
    private void showDialog() {
        DialogUtils.showDialog(this, "确认要申请领取该问题吗？", true, new DialogUtils.OnDialogClickListener() {
            @Override
            public void onCancel(Dialog dialog) {
                dialog.dismiss();
            }

            @Override
            public void onConfirm(Dialog dialog) {
                HashMap<String, String> map = new HashMap<>();
                if ("1".equals(companyType)) {
                    map.put("currentUserId", ownerBean.getRows().getEmployeeId());
                } else if ("2".equals(companyType)) {
                    map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
                }
                map.put("questionId", questionId);
                map.put("flag", "1");
                ServiceRequestManager.getManager().ApplyProblems(ProblemInformationActivity.this, JsonMapUtil.mapToJson(map), ProblemInformationActivity.this);
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onSuccess(int requestId, String result) {
        CommonBean bean = new Gson().fromJson(result, CommonBean.class);
        if (bean.getMessage().getCode() == 200) {
            showCenterSuccessMsg("操作成功");
        } else {
            showCenterInfoMsg(bean.getMessage().getMessage());
        }
        EventBus.getDefault().post(new ProblemPageRefreshEvent());
    }

    @Override
    public void onException(int requestId, String code) {
    }

    public static void OpenActivity(Context context, String requestId, String questionId,
                                    String outsourceFlag) {
        Intent i = new Intent(context, ProblemInformationActivity.class);
        i.putExtra("requestId", requestId);
        i.putExtra("questionId", questionId);
        i.putExtra("outsourceFlag", outsourceFlag);
        context.startActivity(i);
    }

    /**
     *
     * @param context
     * @param requestId
     * @param questionId
     * @param outsourceFlag
     * @param isLook  当从问题列表或者全部列表  进入时候需要传递True  其他界面进入时 不用传
     */
    public static void OpenActivity(Context context, String requestId, String questionId,
                                    String outsourceFlag, boolean isLook) {
        Intent i = new Intent(context, ProblemInformationActivity.class);
        i.putExtra("requestId", requestId);
        i.putExtra("questionId", questionId);
        i.putExtra("outsourceFlag", outsourceFlag);
        i.putExtra("isLook", isLook);
        context.startActivity(i);
    }
}
